import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../models/business_card.dart';
import '../services/database_service.dart';

class BusinessCardEditScreen extends StatefulWidget {
  final BusinessCard? card;

  const BusinessCardEditScreen({super.key, this.card});

  @override
  State<BusinessCardEditScreen> createState() => _BusinessCardEditScreenState();
}

class _BusinessCardEditScreenState extends State<BusinessCardEditScreen> {
  final _formKey = GlobalKey<FormState>();
  final DatabaseService _databaseService = DatabaseService();
  
  late TextEditingController _nameController;
  late TextEditingController _companyController;
  late TextEditingController _positionController;
  late TextEditingController _phoneController;
  late TextEditingController _emailController;
  late TextEditingController _addressController;
  late TextEditingController _websiteController;
  late TextEditingController _notesController;

  bool _isLoading = false;
  bool _isEditing = false;

  @override
  void initState() {
    super.initState();
    _isEditing = widget.card != null;
    
    _nameController = TextEditingController(text: widget.card?.name ?? '');
    _companyController = TextEditingController(text: widget.card?.company ?? '');
    _positionController = TextEditingController(text: widget.card?.position ?? '');
    _phoneController = TextEditingController(text: widget.card?.phone ?? '');
    _emailController = TextEditingController(text: widget.card?.email ?? '');
    _addressController = TextEditingController(text: widget.card?.address ?? '');
    _websiteController = TextEditingController(text: widget.card?.website ?? '');
    _notesController = TextEditingController(text: widget.card?.notes ?? '');
  }

  @override
  void dispose() {
    _nameController.dispose();
    _companyController.dispose();
    _positionController.dispose();
    _phoneController.dispose();
    _emailController.dispose();
    _addressController.dispose();
    _websiteController.dispose();
    _notesController.dispose();
    super.dispose();
  }

  Future<void> _saveBusinessCard() async {
    if (!_formKey.currentState!.validate()) {
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      final now = DateTime.now();
      final businessCard = BusinessCard(
        id: widget.card?.id,
        name: _nameController.text.trim(),
        company: _companyController.text.trim(),
        position: _positionController.text.trim(),
        phone: _phoneController.text.trim(),
        email: _emailController.text.trim(),
        address: _addressController.text.trim(),
        website: _websiteController.text.trim(),
        imagePath: widget.card?.imagePath,
        createdAt: widget.card?.createdAt ?? now,
        updatedAt: now,
        notes: _notesController.text.trim(),
      );

      if (_isEditing) {
        await _databaseService.updateBusinessCard(businessCard);
        _showSuccessSnackBar('名片更新成功');
      } else {
        await _databaseService.insertBusinessCard(businessCard);
        _showSuccessSnackBar('名片保存成功');
      }

      Navigator.pop(context, true);
    } catch (e) {
      _showErrorSnackBar('保存失败: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
      ),
    );
  }

  void _showSuccessSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.green,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_isEditing ? '编辑名片' : '新建名片'),
        backgroundColor: Colors.blue[600],
        foregroundColor: Colors.white,
        actions: [
          TextButton(
            onPressed: _isLoading ? null : _saveBusinessCard,
            child: _isLoading
                ? const SizedBox(
                    width: 20,
                    height: 20,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                    ),
                  )
                : const Text(
                    '保存',
                    style: TextStyle(color: Colors.white, fontSize: 16),
                  ),
          ),
        ],
      ),
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Colors.blue[50]!,
              Colors.white,
            ],
          ),
        ),
        child: Form(
          key: _formKey,
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                // 名片图片预览
                if (widget.card?.imagePath != null) _buildImagePreview(),
                
                // 基本信息
                _buildSectionTitle('基本信息'),
                _buildTextField(
                  controller: _nameController,
                  label: '姓名',
                  icon: Icons.person,
                  validator: (value) {
                    if (value == null || value.trim().isEmpty) {
                      return '請輸入姓名';
                    }
                    return null;
                  },
                ),
                _buildTextField(
                  controller: _companyController,
                  label: '公司',
                  icon: Icons.business,
                  validator: (value) {
                    if (value == null || value.trim().isEmpty) {
                      return '請輸入公司名稱';
                    }
                    return null;
                  },
                ),
                _buildTextField(
                  controller: _positionController,
                  label: '職位',
                  icon: Icons.work,
                  validator: (value) {
                    if (value == null || value.trim().isEmpty) {
                      return '請輸入職位';
                    }
                    return null;
                  },
                ),

                // 联系方式
                _buildSectionTitle('联系方式'),
                _buildTextField(
                  controller: _phoneController,
                  label: '电话',
                  icon: Icons.phone,
                  keyboardType: TextInputType.phone,
                  validator: (value) {
                    if (value == null || value.trim().isEmpty) {
                      return '请输入电话号码';
                    }
                    return null;
                  },
                ),
                _buildTextField(
                  controller: _emailController,
                  label: '电子邮件',
                  icon: Icons.email,
                  keyboardType: TextInputType.emailAddress,
                  validator: (value) {
                    if (value == null || value.trim().isEmpty) {
                      return '请输入电子邮件';
                    }
                    if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(value)) {
                      return '请输入有效的电子邮件地址';
                    }
                    return null;
                  },
                ),

                // 其他信息
                _buildSectionTitle('其他信息'),
                _buildTextField(
                  controller: _addressController,
                  label: '地址',
                  icon: Icons.location_on,
                  maxLines: 2,
                ),
                _buildTextField(
                  controller: _websiteController,
                  label: '网站',
                  icon: Icons.language,
                  keyboardType: TextInputType.url,
                ),
                _buildTextField(
                  controller: _notesController,
                  label: '备注',
                  icon: Icons.note,
                  maxLines: 3,
                ),

                const SizedBox(height: 20),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildImagePreview() {
    return Container(
      margin: const EdgeInsets.only(bottom: 20),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child: Image.network(
          widget.card!.imagePath!,
          width: double.infinity,
          height: 200,
          fit: BoxFit.cover,
          errorBuilder: (context, error, stackTrace) {
            return Container(
              height: 200,
              color: Colors.grey[200],
              child: const Center(
                child: Icon(
                  Icons.image,
                  size: 50,
                  color: Colors.grey,
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Container(
      margin: const EdgeInsets.only(top: 20, bottom: 12),
      child: Row(
        children: [
          Text(
            title,
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: Colors.blue[800],
            ),
          ),
          const SizedBox(width: 8),
          Container(
            height: 2,
            width: 30,
            color: Colors.blue[600],
          ),
        ],
      ),
    );
  }

  Widget _buildTextField({
    required TextEditingController controller,
    required String label,
    required IconData icon,
    TextInputType? keyboardType,
    int maxLines = 1,
    String? Function(String?)? validator,
  }) {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      child: TextFormField(
        controller: controller,
        keyboardType: keyboardType,
        maxLines: maxLines,
        validator: validator,
        decoration: InputDecoration(
          labelText: label,
          prefixIcon: Icon(icon, color: Colors.blue[600]),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
            borderSide: BorderSide(color: Colors.grey[300]!),
          ),
          enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
            borderSide: BorderSide(color: Colors.grey[300]!),
          ),
          focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
            borderSide: BorderSide(color: Colors.blue[600]!, width: 2),
          ),
          errorBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
            borderSide: const BorderSide(color: Colors.red),
          ),
          focusedErrorBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
            borderSide: const BorderSide(color: Colors.red, width: 2),
          ),
          filled: true,
          fillColor: Colors.white,
          contentPadding: const EdgeInsets.symmetric(
            horizontal: 16,
            vertical: 16,
          ),
        ),
      ),
    );
  }
}
